package com.cdu.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.cdu.pojo.User;

import java.util.Date;
import java.util.Map;

/**
 * @program: easy-help-v2
 * @description:
 * @author: hanabi
 * @create: 2022-05-19 10:16
 **/

public class JWTUtil {

    private static final String SECRET = "#$cdu.easy.help$#";

    private static final String ISSUER = "easy-help";
    //过期时间
//    private static final Long EXPIRE_DATE = 1000 * 60 * 5L;
    private static final Long EXPIRE_DATE = 1000 * 60 * 60 * 24 * 7L;

    /**
     * 通过User生成token
     **/
    public static String createToken(User user) {
        return JWT.create()
                .withIssuer(ISSUER)
                .withIssuedAt(new Date())
                .withClaim("userId", user.getId())
                .withClaim("role", user.getRole())
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE_DATE))
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 通过Map生成token
     **/
    public static String createToken(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k, v) -> builder.withClaim(k, v));
        return builder
                .withIssuer(ISSUER)
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE_DATE))
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 验证token
     **/
    public static boolean verifyToken(String token) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        try {
            JWT.require(Algorithm.HMAC256(SECRET))
                    .build()
                    .verify(token);
            return true;
        } catch (SignatureVerificationException e) {
            //验证的签名不一致
            throw new SignatureVerificationException(algorithm);
        } catch (TokenExpiredException e) {
            throw new TokenExpiredException("token 已过期");
        } catch (AlgorithmMismatchException e) {
            throw new AlgorithmMismatchException("签名算法不匹配");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
